package com.my.sort;

import com.my.domain.OrderStep;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.util.ArrayList;
import java.util.List;

//保证消息的顺序性
public class Producer2 {
    public static void main(String[] args) throws MQClientException, RemotingException, InterruptedException, MQBrokerException {
        DefaultMQProducer producer = new DefaultMQProducer("group1");
        producer.setNamesrvAddr("localhost:9876");
        producer.start();

        List<OrderStep> orderSteps = generateOrderList();
        for (OrderStep orderStep : orderSteps) {
            Message message = new Message("topic11", "tag1", orderStep.toString().getBytes());
            SendResult sendResult = producer.send(message, new MessageQueueSelector() {//发送消息时选择队列
                @Override
                public MessageQueue select(List<MessageQueue> list, Message message, Object o) {
                    //保证order的id对应同一个队列
                    int size = list.size();//队列数
                    int mod = orderStep.getId() % size;//取模
                    return list.get(mod);//选取队列
                }
            },null);
            System.out.println(sendResult);
        }
        producer.shutdown();
    }

    private static List<OrderStep> generateOrderList(){//模拟按照顺序生成5个订单的相关步骤
        List<OrderStep> list = new ArrayList<>();
        String[] descs = {"创建","付款","推送","完成"};
        for (int i = 1; i <= 5; i++) {
            for (int j = 0; j < 4; j++) {
                OrderStep orderStep = new OrderStep(i,descs[j]);
                list.add(orderStep);
            }
        }
        return list;
    }
}
